/* @flow */
'use strict';
import {
    StyleSheet,
    View,
    Navigator,
    Text,
    TouchableOpacity,
    TouchableHighlight,
    TextInput,
    AlertIOS,
    AsyncStorage,
} from 'react-native';
import React from 'react';
import DeviceInfo from 'react-native-device-info';
import Icon from 'react-native-vector-icons/Ionicons';
import URL from '../config/server';
import {Utils} from '../config/utils';


const NavigationBarRouteMapper = {
    LeftButton(route, navigator, index, navState) {
        return (
            <TouchableOpacity style={{flex: 1, justifyContent: 'center'}}
                              onPress={() => navigator.parentNavigator.pop()}>
                <View style={{flexDirection:'row',padding:5}}>
                    <Icon name="ios-arrow-back" size={18} color="#ffffff" style={{alignSelf:'center'}}/>
                    <Text style={{color: 'white', margin: 3,fontSize:16}}>
                        返回
                    </Text>
                </View>
            </TouchableOpacity>
        );
    },
    RightButton(route, navigator, index, navState) {
        return null;
    },
    Title(route, navigator, index, navState) {
        return (
            <Text style={{color: 'white', margin: 10, fontSize: 20}}>
                设置密码
            </Text>
        );
    }
};


export default class RegPhone2 extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            checkcode: '',
            pwd: '',
            pwd2: '',
            available: false,
            timer: 60,
            validCode: '',
            codeError: false,
            pwdError: false,
            pwd2Error: false,
            inviteError: false,
            inviteCode: '',
            isSubmit: false
        };
    }

    componentWillUnmount() {
        console.log('Unmount!');
        clearInterval(this._interval);
    }

    componentDidMount() {
        let available = this.state.available;
        this._interval = setInterval(this.Count.bind(this), 1000);
        this.getCode();

    }

    getCode() {
        const GET_CODE = URL.getCode + this.props.message + '/';
        console.log(GET_CODE);
        fetch(GET_CODE, {
            method: "GET",
            mode: 'no-cors'
        }).then((response) => response.json())
            .then((responseData) => {
                console.log(responseData);
            }).catch(function (e) {
                console.log(e);
                AlertIOS.alert(
                    '温馨提示',
                    '网络连接错误，请关闭飞行模式或检查您的网络连接。'
                )
            })
            .done();
    }

    Count() {
        this.setState({
            timer: this.state.timer - 1
        });
        if (this.state.timer == 0) {
            console.log("run!");
            this.setState({
                available: true,
                timer: null
            });
            clearInterval(this._interval);
        }
    }


    checkInviteCode() {
        const CHECK_INVITE = URL.local + 'checkInviteCode?code=' + this.state.inviteCode;
        console.log(CHECK_INVITE);
        fetch(CHECK_INVITE, {
            method: "GET",
            mode: 'no-cors'
        }).then((response) => response.json())
            .then((responseData) => {
                console.log(responseData);
                if (responseData) {
                    console.log('data valid!');
                    this.postMsg();
                } else {
                    this.setState({
                        inviteError: true
                    })
                }
            }).catch(function (e) {
                console.log(e);
                AlertIOS.alert(
                    '温馨提示',
                    '网络连接错误，请关闭飞行模式或检查您的网络连接。'
                )
            })
            .done();
    }


    checkCode(checkcode) {
        const CHECK_CODE = URL.checkCode + 'telphone/' + this.props.message + '/' + checkcode;
        console.log(CHECK_CODE);
        fetch(CHECK_CODE, {
            method: "GET",
            mode: 'no-cors'
        }).then((response) => response.json())
            .then((responseData) => {
                console.log(responseData);
                if (responseData) {
                    this.checkInviteCode();
                } else {
                    this.setState({
                        codeError: true
                    })
                }
            }).catch(function (e) {
                console.log(e);
                AlertIOS.alert(
                    '温馨提示',
                    '网络连接错误，请关闭飞行模式或检查您的网络连接。'
                )
            })
            .done();
    }

    postMsg() {
        let that = this;
        that.setState({isSubmit: true});
        var REGISTER = URL.register + 'telphone';
        console.log(REGISTER);
        console.log(this.props.message + this.state.pwd2 + this.state.inviteCode);
        let MSG = {
            telphone: this.props.message,
            password: this.state.pwd2,
            machineId: DeviceInfo.getUniqueID(),
            byzd1: this.state.inviteCode
        };

        Utils.post(REGISTER, MSG, function (data) {
            if (data) {
                AlertIOS.alert(
                    '注册成功!'
                );
                that.props.navigator.push({
                    id: 'LoginPage',
                    message: {
                        title: '神秘涨停网',
                        regPhone: that.props.message
                    }
                })
            } else {
                that.setState({isSubmit: false})
            }
        })
    }

    onPress() {
        let checkcode = this.state.checkcode;
        let pwd = this.state.pwd;
        let pwd2 = this.state.pwd2;
        const Reg = /^(\w){6,18}$/;

        //重置错误信息
        this.setState({codeError: false});
        this.setState({pwdError: false});
        this.setState({pwd2Error: false});

        if (checkcode == '') {
            this.setState({codeError: true});
        } else if (pwd == '') {
            this.setState({pwdError: true});
        } else if (pwd2 == '') {
            this.setState({pwd2Error: true});
        } else {
            if (!Reg.test(pwd)) {
                this.setState({pwdError: true});
            } else if (pwd != pwd2) {
                this.setState({pwd2Error: true});
            } else {
                this.checkCode(checkcode);
            }
        }
    }

    sendAgain() {
        if (!this.state.available) {
            console.log("can't press!!");
        } else {
            console.log("send checkcode again !");
            this.getCode();
            this.setState({
                timer: 60,
                available: false
            });
            this._interval = setInterval(this.Count.bind(this), 1000);
        }
    }

    renderScene(route, navigator) {
        return (
            <View style={styles.container} ref="form">
                <View style={styles.inline}>
                    <TextInput
                        placeholder="请输入验证码"
                        style={styles.checkCode}
                        onChangeText={(checkcode) => this.setState({checkcode})}
                        value={this.state.checkcode}
                    />
                    <TouchableHighlight style={this.state.available?styles.checkButtonT:styles.checkButtonF}
                                        onPress={this.sendAgain.bind(this)} underlayColor='#a9a9a9'>
                        <Text style={styles.checkText}>重新发送{this.state.timer}</Text>
                    </TouchableHighlight>
                </View>
                {
                    this.state.codeError ?
                        <View>
                            <Text style={styles.error}>
                                请输入正确的验证码.
                            </Text>
                        </View> : null
                }
                <TextInput
                    secureTextEntry={true}
                    placeholder="请输入新密码"
                    style={styles.pwd}
                    onChangeText={(pwd) => this.setState({pwd})}
                    value={this.state.pwd}
                />
                {
                    this.state.pwdError ?
                        <View>
                            <Text style={styles.error}>
                                密码长度在6~18之间，只能包含字符、数字或下划线.
                            </Text>
                        </View> : null
                }
                <TextInput
                    secureTextEntry={true}
                    placeholder="请再次输入新密码"
                    style={styles.pwd}
                    onChangeText={(pwd2) => this.setState({pwd2})}
                    value={this.state.pwd2}
                />
                {this.state.pwd2Error ?
                    <View style={this.state.pwd2Error?styles.error:styles.noerror}>
                        <Text style={styles.error}>
                            两次密码输入的不一致.
                        </Text>
                    </View> : null}
                <TextInput
                    placeholder="邀请码"
                    style={styles.pwd}
                    onChangeText={(inviteCode) => this.setState({inviteCode})}
                    value={this.state.inviteCode}
                />
                {this.state.inviteError ?
                    <View style={this.state.inviteError?styles.error:styles.noerror}>
                        <Text style={styles.error}>
                            无效的邀请码
                        </Text>
                    </View> : null}
                <TouchableHighlight style={this.state.isSubmit?styles.forbButton:styles.button}
                                    onPress={this.state.isSubmit?()=>console.log('forbid'):this.onPress.bind(this)}
                                    underlayColor='#e02820'>
                    <Text style={styles.buttonText}>{this.state.isSubmit ? "正在注册.." : "立即注册"}</Text>
                </TouchableHighlight>
            </View>
        );
    }


    render() {
        return (
            <Navigator
                ref='main'
                renderScene={this.renderScene.bind(this)}
                navigator={this.props.navigator}
                navigationBar={
            <Navigator.NavigationBar 
                style={{backgroundColor: '#e02820', alignItems: 'center'}}
                routeMapper={NavigationBarRouteMapper} />
          	}/>
        );
    }
}


const styles = StyleSheet.create({
    container: {
        marginTop: 100,
        justifyContent: 'center',
        padding: 20,
        backgroundColor: '#ffffff'
    },
    invisiable: {
        height: 0
    },
    inline: {
        flex: 1,
        height: 36,
        flexDirection: 'row',
        marginBottom: 15
    },
    pwd: {
        color: '#000000',
        fontSize: 17,
        height: 36,
        padding: 7,
        borderRadius: 4,
        borderColor: '#cccccc',
        borderWidth: 1,
        marginBottom: 15
    },
    checkCode: {
        flex: 3,
        color: '#000000',
        fontSize: 17,
        height: 36,
        padding: 7,
        borderRadius: 4,
        borderColor: '#cccccc',
        borderWidth: 1
    },
    checkText: {
        fontSize: 17,
        color: 'white',
        alignSelf: 'center',
        marginTop: 8
    },
    noerror: {
        height: 0
    },
    error: {
        color: '#a94442',
        fontSize: 15,
        marginBottom: 7,
        fontWeight: 'bold'
    },
    checkButtonF: {
        flex: 2,
        height: 36,
        backgroundColor: '#a9a9a9',
        borderColor: '#a9a9a9',
        borderWidth: 1,
        borderBottomRightRadius: 8,
        borderTopRightRadius: 8,
        marginLeft: -10
    },
    checkButtonT: {
        flex: 2,
        height: 36,
        backgroundColor: '#e02820',
        borderColor: '#e02820',
        borderWidth: 1,
        borderBottomRightRadius: 8,
        borderTopRightRadius: 8,
        marginLeft: -10
    },
    buttonText: {
        fontSize: 18,
        color: 'white',
        alignSelf: 'center'
    },
    button: {
        height: 36,
        backgroundColor: '#e02820',
        borderColor: '#e02820',
        borderWidth: 1,
        borderRadius: 8,
        marginBottom: 10,
        alignSelf: 'stretch',
        justifyContent: 'center'
    },
    findPwdText: {
        fontSize: 15,
        textDecorationLine: 'underline',
        textAlign: 'right'
    },
    forbButton: {
        height: 36,
        backgroundColor: '#333333',
        borderColor: '#333333',
        borderWidth: 1,
        borderRadius: 8,
        marginBottom: 10,
        alignSelf: 'stretch',
        justifyContent: 'center'
    }
});

